package com.winit.openapi.isp.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.isp.ISPOrderService;
import com.winit.oms.spi.isp.command.GetSPOrderChargeCommand;
import com.winit.oms.spi.isp.command.order.ISPOrderSearchCommand;
import com.winit.oms.spi.isp.vo.ISPOrder;
import com.winit.oms.spi.isp.vo.SPOrderChargeVO;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * ISP索赔单Controller
 * <Change to the actual description of this class>
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * jian.ma 	1.0  		2016年12月6日 	Created
 *
 * </pre>
 * @since 1.
                       .::::.
                     .::::::::.
                    :::::::::::
                 ..:::::::::::'
              '::::::::::::'
                .::::::::::
           '::::::::::::::..
                ..::::::::::::::.
              ``::::::::::::::::::    妹子保佑，永无bug
               ::::``:::::::::::'      .:::.
              ::::'   ':::::'       .::::::::.
            .::::'      ::::     .:::::::'::::.
           .:::'       :::::  .:::::::::' ':::::.
          .::'        :::::.:::::::::'      ':::::.
         .::'         ::::::::::::::'         ``::::.
     ...:::           ::::::::::::'              ``::.
    ```` ':.          ':::::::::'                  ::::..
                       '.:::::'                    ':'````..
 */
@Controller
public class ISPSPOrderController extends BaseController {
    
    @Resource
    private ISPOrderService iSPOrderService;
    
    @RequestMapping(value = "/isp/order/getISPOrdersStatus")
    public String getISPOrdersStatus(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	 Object obj = requestMsg.getData();
    	 
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			ValidateUtil.validNotNull(json, "orderNos");
			List<ISPOrder> orderList = iSPOrderService.getISPOrdersStatus(json.getString("orderNos"));
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("orderList", orderList);
			responseMsg.setData(result);
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		return SUCCESS;

    }
    
    


	@RequestMapping(value = "/isp/order/SPOrderList")
    public String sPOrderList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        
        Object obj = requestMsg.getData();

        ISPOrderSearchCommand command = null;

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validSearch(json);
            command = buildSearchCommand(json);
            Searchable<?> searchable = buildSearchPageParams(json);
            command.setSearchable(searchable);
        }  else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        

        // 调用接口分页查询订单
        Page<ISPOrder> pagelist = iSPOrderService.getISPSPOrderList(command);
        if (pagelist != null) {
            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pagelist.getPageable().getPageNumber());
            pageMap.put("pageSize", pagelist.getPageable().getPageSize());
            pageMap.put("totalCount", pagelist.getTotalElements());

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", pagelist.getContent());
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }
        
        return SUCCESS;
    }

    private void validSearch(JSONObject json) {
        // status
        ValidateUtil.validNotNull(json, "status");
        ValidateUtil.validMaxLength(json, "status", 10);
        // expressNo
        ValidateUtil.validMaxLength(json, "expressNo", 60);
        // winitProductCode
        ValidateUtil.validMaxLength(json, "winitProductCode", 60);
        // orderDateStart
        ValidateUtil.validNotNull(json, "orderDateStart");
        ValidateUtil.validDateString(json, "orderDateStart", DateUtil.SIMPLE_DATE_STRING);
        // orderDateEnd
        ValidateUtil.validNotNull(json, "orderDateEnd");
        ValidateUtil.validDateString(json, "orderDateEnd", DateUtil.SIMPLE_DATE_STRING);
        ValidateUtil.validDateBefore(json, "orderDateStart", "orderDateEnd");

        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");

                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");

                if (isExistValue(pageParams, "pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (isExistValue(pageParams, "pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }
    
    private ISPOrderSearchCommand buildSearchCommand(JSONObject json) {
        ISPOrderSearchCommand command = new ISPOrderSearchCommand();
        if (json.containsKey("orderNos")) {
            command.setOrderNo(StringUtils.trim(json.getString("orderNos")));
        }
        // winitProductCode
        if (json.containsKey("winitProductCode")) {
            command.setWinitProductCode(json.getString("winitProductCode"));
        }
        // warehouseCode
        if (json.containsKey("warehouseCode")) {
            command.setWarehouseCode(json.getString("warehouseCode"));
        }
        // warehouseCode
        if (json.containsKey("status")) {
            List<String> status = new ArrayList<String>();
            status.add(json.getString("status"));
            command.setStatus(status);
        }
        // orderDateStart
        if (json.containsKey("orderDateStart")) {
            String orderDateStart = json.getString("orderDateStart");
            orderDateStart += " 00:00:00";
            Date from = DateUtil.parse2Date(orderDateStart, DateUtil.FULL_DATE_STRING);
            command.setDateFrom(from);
        }
        // orderDateEnd
        if (json.containsKey("orderDateEnd")) {
            String orderDateEnd = json.getString("orderDateEnd");
            orderDateEnd += " 23:59:59";
            Date to = DateUtil.parse2Date(orderDateEnd, DateUtil.FULL_DATE_STRING);
            command.setDateTo(to);
        }

        return command;
    }
    
    private Searchable<?> buildSearchPageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (isExistValue(json, "pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");

            if (ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                pageNo = pageParams.getInteger("pageNo");
                if (pageNo <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                }
            } else if (isExistValue(pageParams, "pageNo") && !ValidateUtil.isIntNumber(pageParams.getString("pageNo"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageNo");
            }

            if (ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                pageSize = pageParams.getInteger("pageSize");
                if (pageSize <= 0) {
                    throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                }
            } else if (isExistValue(pageParams, "pageSize")
                       && !ValidateUtil.isIntNumber(pageParams.getString("pageSize"))) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageSize");
            }

        }
        Searchable<?> search = Searchable.newSearchable();
        search.setPage(pageNo, pageSize);
        search.addSort(new Sort(Direction.ASC, "CREATED"));
        return search;
    }
    
    
    
    @RequestMapping(value = "/isp/order/UpdateSPOrderList")
    public String updateSPOrderList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        
        Object obj = requestMsg.getData();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validupdateSPOrderList(json);
            iSPOrderService.batchUpdateClaimOrderList(json.getString("orderNos"), json.getString("claimStatus"));
        }  else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
       
        
        return SUCCESS;
    }

    private void validupdateSPOrderList(JSONObject json) {
        ValidateUtil.validNotNull(json, "orderNos");
        ValidateUtil.validNotNull(json, "claimStatus");
    }
    

    
    @RequestMapping(value = "/isp/order/SPCharge")
    public String SPCharge(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        
        Object obj = requestMsg.getData();

        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validList(json, "orderNoList", true);
            JSONArray orderNoArr = json.getJSONArray("orderNoList");
            List<String> orderNoList = new ArrayList<String>();
            for(int i=0;i<orderNoArr.size();i++){
                JSONObject item = orderNoArr.getJSONObject(i);
                ValidateUtil.validNotNull(item, "orderNo");
                orderNoList.add(item.getString("orderNo"));
            }
            GetSPOrderChargeCommand command = new GetSPOrderChargeCommand();
            command.setCtx(CommandContext.getContext());
            command.setOrderNoList(orderNoList);
            List<SPOrderChargeVO> chargeVO = iSPOrderService.getSPOrderChargeList(command);
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("orderList", chargeVO);
            responseMsg.setData(result);
        }  else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        
        return SUCCESS;
    }

}
